﻿using System.Collections.Generic;
using System.Diagnostics;
using System.Windows.Forms;
using Mbs.Elements;
using Mbs.Modularity.AddIns;
using Mbs.ComponentModel.Container;

namespace Mbs.Windows.Elements.Builders
{
    [Component(Id = "ContextMenuStrip", Service = typeof(IElementBuilder))]
    public class ContextMenuStripBuilder : ElementBuilder
    {
        public override object Create(object caller, IAddInItem element)
        {
            Debug.Assert(element != null, "element == null");

            var dropDownMenu = new ContextMenuStrip();
            dropDownMenu.Name = element.Path;
            dropDownMenu.Tag = element;

            var disposeCollector = caller as IDisposeCollector;
            if (disposeCollector != null)
                disposeCollector.Disposes.Add(new DisposeAction(dropDownMenu, () => dropDownMenu.Dispose()));

            element.Path.RegisterSite(dropDownMenu);

            return dropDownMenu;

        }

        public override void InitInstance(object caller, IAddInItem element, List<object> subItems, object instance)
        {
            if (subItems == null || instance == null) return;

            var dropDownMenu = instance as ToolStripDropDownMenu;
            if (dropDownMenu != null)
            {
                foreach (var item in subItems)
                    if (item is ToolStripItem) 
                        element.Path.Site().Add(item, null);
            }
        }
    }
}
